package com.jjty.dataGenerator.jserji.service;

import com.alibaba.fastjson.JSONObject;
import com.jjty.dataGenerator.jserji.entity.JsResponse;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@Service
public class JsDataReportService {

    @Value("${spring.datasource.url}")
    private String dbUrl;
    @Value("${spring.datasource.username}")
    private String dbUsername;
    @Value("${spring.datasource.password}")
    private String dbPassword;

    private String sendPostRequest(String url, String encryptedParam) throws IOException {
        // 创建包含 encryptedParam 和 factorySign 的 JSON 对象
        JSONObject requestJson = new JSONObject();
        requestJson.put("content", encryptedParam);
        requestJson.put("factorySign", "xfy");

        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(requestJson.toJSONString(), "UTF-8"));

        HttpResponse response = httpClient.execute(httpPost);
        return EntityUtils.toString(response.getEntity(), "UTF-8");
    }

    public void reportData(String dataType, String url) {
        List<String> dataList = getDataFromDatabase(dataType);
        Logger log = LoggerFactory.getLogger(getClass());
        int totalCount = 0;
        int successCount = 0;
        int failureCount = 0;

        for (String encryptedParam : dataList) {
            totalCount++;
            log.info("提报加密数据：" + encryptedParam); // 日志记录加密参数（实际使用时可能需要脱敏）

            try {
                // 直接发送加密参数，不再进行JSON转换
                String responseBody = sendPostRequest(url, encryptedParam);

                if (responseBody != null && !responseBody.isEmpty()) {
                    log.info("dataReport--->" + responseBody);
                    JsResponse jsResponse = JSONObject.parseObject(responseBody, JsResponse.class);

                    if (jsResponse == null) {
                        log.error("未响应推送结果！跳过加密数据：" + maskSensitiveData(encryptedParam));
                        failureCount++;
                        continue;
                    }

                    if (jsResponse.getCode() != 200) {
                        log.error("上报失败，错误信息：" + jsResponse.getMsg() + "，跳过加密数据：" + maskSensitiveData(encryptedParam));
                        failureCount++;
                    } else {
                        successCount++;
                    }
                } else {
                    log.error("上报失败，无响应内容，跳过加密数据：" + maskSensitiveData(encryptedParam));
                    failureCount++;
                }
            } catch (IOException e) {
                log.error("发送请求时发生异常，跳过加密数据：" + maskSensitiveData(encryptedParam), e);
                failureCount++;
            }
        }

        log.info("数据上报完成！总数据量：" + totalCount + "，成功：" + successCount + "，失败：" + failureCount);
    }

    // 敏感数据脱敏处理（可选）
    private String maskSensitiveData(String data) {
        if (data == null || data.length() <= 8) {
            return data;
        }
        return data.substring(0, 4) + "*****" + data.substring(data.length() - 4);
    }

    private List<String> getDataFromDatabase(String dataType) {
        List<String> dataList = new ArrayList<>();
        String sql = "SELECT encoded_data FROM js_device_data WHERE data_type = '" + dataType + "'";
        Logger log = LoggerFactory.getLogger(getClass());
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                // 从结果集中获取 JSON 字符串
                String jsonStr = rs.getString("encoded_data");
                if (jsonStr != null) {
                    // 将 JSON 字符串解析为 JSONObject
                    //JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    dataList.add(jsonStr);
                }
            }
        } catch (Exception e) {
            log.error("从数据库查询数据时发生异常", e);
        }
        return dataList;
    }
}
